package com.qq.clone.commonAuth.Config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

// JWT 工具类
@Component
public class JwtUtils {
    @Value("${jwt.secret}")
    private String SECRET = "";

    @Value("${jwt.expiration}")
    private long EXPIRATION = 0;

    private SecretKey KEY;

    @PostConstruct
    public void init() {
        KEY = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
    }

    /* 生成token */
    public String generateToken(String username, Long userId) {
        return Jwts.builder()
                .subject(username)
                .claim("userId", userId)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(KEY, Jwts.SIG.HS256)
                .compact();
    }

    public Claims parseToken(String token) throws JwtException {
        return Jwts.parser()
                .verifyWith(KEY)
                .build()
                .parseSignedClaims(token) // 验证签名
                .getPayload();
        /*
         * 负载 eg:
         * {
         *   "sub": "name",
         *   "roles": ["USER", "ADMIN"],
         *   "iat": 1712345678,
         *   "exp": 1712349278
         * }
         * */
    }
}
